/**
 * 游戏管理器 - 纯标签页版本（无滚动）
 * 所有内容通过标签切换，完全不需要滚动
 */

import { GAME_CONFIG } from './config/game-config.js';
import { StorageManager } from './managers/StorageManager.js';
import { ResourceManager } from './managers/ResourceManager.js';
import { BuildingManager } from './managers/BuildingManager.js';
import { EventManager } from './managers/EventManager.js';
import { VillagerManager } from './managers/VillagerManager.js';

class GameManager {
    constructor() {
        this.isInitialized = false;
        this.gameData = null;
        this.gameContainer = null;
        this.currentTab = 'overview';

        this.storageManager = new StorageManager();
        this.resourceManager = null;
        this.buildingManager = null;
        this.eventManager = null;
        this.villagerManager = null;

        this.timers = {
            resourceUpdate: null,
            eventCheck: null,
            autoSave: null
        };
    }

    async init(containerId) {
        if (this.isInitialized) return;

        this.gameContainer = document.getElementById(containerId);
        if (!this.gameContainer) {
            console.error('游戏容器未找到:', containerId);
            return;
        }

        try {
            await this.loadGameData();
            this.initializeManagers();
            await this.initGameInterface();
            this.setupTabSwitching();
            this.setupEventListeners();
            this.startTimers();
            this.checkDailyLogin();

            this.isInitialized = true;
            console.log('游戏初始化完成');
            this.showNotification('欢迎来到镇长日志游戏！', 'success');
            this.updateAllTabs();

        } catch (error) {
            console.error('游戏初始化失败:', error);
            this.showError('游戏初始化失败，请刷新页面重试');
        }
    }

    async loadGameData() {
        let data = this.storageManager.loadGameData();
        if (!data) {
            data = this.storageManager.getInitialGameData();
        }
        this.gameData = data;
    }

    initializeManagers() {
        this.resourceManager = new ResourceManager(this.gameData);
        this.buildingManager = new BuildingManager(this.gameData, this.resourceManager);
        this.eventManager = new EventManager(this.gameData, this.resourceManager, this.buildingManager);
        this.villagerManager = new VillagerManager(this.gameData, this.resourceManager);
        this.resourceManager.updateResourcesBasedOnTime();
    }

    showError(message) {
        if (!this.gameContainer) return;
        this.gameContainer.innerHTML = `
            <div class="empty-state">
                <i class="fa fa-exclamation-circle"></i>
                <p>${message}</p>
                <button class="btn btn-primary" onclick="location.reload()" style="max-width: 200px; margin-top: 1rem;">
                    <i class="fa fa-refresh"></i>
                    <span>刷新页面</span>
                </button>
            </div>
        `;
    }

    showNotification(message, type = 'info') {
        if (window.showNotification) {
            window.showNotification(message, '', type);
        }
    }

    /**
     * 初始化游戏界面 - 所有标签页
     */
    async initGameInterface() {
        if (!this.gameContainer) return;

        this.gameContainer.innerHTML = `
            <!-- 总览标签页 -->
            <div class="tab-content active" id="tab-overview">
                <div class="overview-grid">
                    <!-- 资源卡片 -->
                    <div class="resources-row" id="resources-row"></div>

                    <!-- 状态信息 -->
                    <div class="info-cards-grid">
                        <div class="info-card-small">
                            <div class="info-card-label">
                                <i class="fa fa-flag"></i>
                                当前阶段
                            </div>
                            <div class="info-card-value" id="game-stage">生存阶段</div>
                        </div>
                        <div class="info-card-small">
                            <div class="info-card-label">
                                <i class="fa fa-users"></i>
                                人口
                            </div>
                            <div class="info-card-value" id="game-population">5/10</div>
                        </div>
                        <div class="info-card-small">
                            <div class="info-card-label">
                                <i class="fa fa-calendar"></i>
                                游戏天数
                            </div>
                            <div class="info-card-value" id="game-day">第1天</div>
                        </div>
                        <div class="info-card-small">
                            <div class="info-card-label">
                                <i class="fa fa-bell"></i>
                                待处理事件
                            </div>
                            <div class="info-card-value" id="events-count">0</div>
                        </div>
                    </div>

                    <!-- 快捷操作 -->
                    <div class="quick-actions">
                        <button id="recruit-villager-quick" class="btn btn-primary">
                            <i class="fa fa-user-plus"></i>
                            <span>招募村民</span>
                        </button>
                        <button onclick="document.querySelector('[data-tab=buildings]').click()" class="btn btn-secondary">
                            <i class="fa fa-building"></i>
                            <span>管理建筑</span>
                        </button>
                    </div>
                </div>
            </div>

            <!-- 建筑标签页 -->
            <div class="tab-content" id="tab-buildings">
                <div class="content-list" id="buildings-list"></div>
            </div>

            <!-- 事件标签页 -->
            <div class="tab-content" id="tab-events">
                <div class="content-list" id="events-list"></div>
            </div>

            <!-- 村民标签页 -->
            <div class="tab-content" id="tab-villagers">
                <div class="empty-state">
                    <i class="fa fa-users"></i>
                    <p>村民管理功能即将上线</p>
                    <p style="font-size: 0.8rem; opacity: 0.7; margin-top: 0.5rem;">
                        将支持查看村民信息、分配工作等功能
                    </p>
                </div>
            </div>

            <!-- 日志标签页 -->
            <div class="tab-content" id="tab-logs">
                <div class="logs-container" id="game-log"></div>
            </div>
        `;

        this.addLog('游戏初始化完成');
        this.addLog('欢迎来到镇长日志游戏！');
    }

    /**
     * 设置标签页切换
     */
    setupTabSwitching() {
        const tabs = document.querySelectorAll('.main-tab');
        const contents = document.querySelectorAll('.tab-content');

        tabs.forEach(tab => {
            tab.addEventListener('click', () => {
                const tabId = tab.getAttribute('data-tab');

                // 更新标签激活状态
                tabs.forEach(t => t.classList.remove('active'));
                tab.classList.add('active');

                // 更新内容显示
                contents.forEach(content => {
                    content.classList.remove('active');
                });
                document.getElementById(`tab-${tabId}`).classList.add('active');

                this.currentTab = tabId;

                // 更新对应标签页内容
                this.updateTabContent(tabId);
            });
        });
    }

    setupEventListeners() {
        // 总览页招募按钮
        const recruitBtn = document.getElementById('recruit-villager-quick');
        if (recruitBtn) {
            recruitBtn.addEventListener('click', () => this.handleRecruitVillager());
        }
    }

    startTimers() {
        this.timers.resourceUpdate = setInterval(() => {
            this.resourceManager.updateResourcesBasedOnTime();
            this.updateResourcesDisplay();
        }, GAME_CONFIG.RESOURCE_UPDATE_INTERVAL);

        this.timers.eventCheck = setInterval(() => {
            this.checkAndGenerateEvent();
        }, GAME_CONFIG.EVENT_CHECK_INTERVAL);

        setTimeout(() => this.checkAndGenerateEvent(), GAME_CONFIG.INITIAL_EVENT_DELAY);

        this.timers.autoSave = setInterval(() => {
            this.saveGame();
        }, GAME_CONFIG.AUTO_SAVE_INTERVAL);
    }

    checkAndGenerateEvent() {
        const event = this.eventManager.generateRandomEvent();
        if (event) {
            this.eventManager.addEvent(event);
            this.updateEventsDisplay();
            this.addLog(`新事件: ${event.name}`);
            this.showNotification(`发生新事件: ${event.name}`, 'warning');

            // 更新总览页的事件计数
            this.updateEventsCount();
        }
    }

    saveGame() {
        this.storageManager.saveGameData(this.gameData);
    }

    checkDailyLogin() {
        const now = new Date();
        const lastLogin = new Date(this.gameData.lastLogin || 0);

        if (now.toDateString() !== lastLogin.toDateString()) {
            this.gameData.consecutiveDays = (this.gameData.consecutiveDays || 0) + 1;

            const reward = {
                wood: GAME_CONFIG.DAILY_REWARD.WOOD_PER_DAY * this.gameData.consecutiveDays,
                food: GAME_CONFIG.DAILY_REWARD.FOOD_PER_DAY * this.gameData.consecutiveDays
            };

            this.resourceManager.addResource('wood', reward.wood);
            this.resourceManager.addResource('food', reward.food);

            this.gameData.lastLogin = now.getTime();
            this.saveGame();

            this.showNotification(
                `第${this.gameData.consecutiveDays}天签到! 获得${reward.wood}木材和${reward.food}粮食`,
                'success'
            );
            this.addLog(`签到奖励: +${reward.wood}木材, +${reward.food}粮食`);
        }
    }

    /**
     * 更新所有标签页
     */
    updateAllTabs() {
        this.updateResourcesDisplay();
        this.updateBuildingsDisplay();
        this.updateEventsDisplay();
        this.updateGameInfo();
    }

    /**
     * 更新特定标签页内容
     */
    updateTabContent(tabId) {
        switch (tabId) {
            case 'overview':
                this.updateResourcesDisplay();
                this.updateGameInfo();
                break;
            case 'buildings':
                this.updateBuildingsDisplay();
                break;
            case 'events':
                this.updateEventsDisplay();
                break;
        }
    }

    /**
     * 更新资源显示
     */
    updateResourcesDisplay() {
        const container = document.getElementById('resources-row');
        if (!container) return;

        const resourcesInfo = this.resourceManager.getResourcesInfo();
        container.innerHTML = '';

        // 木材
        container.appendChild(this.createResourceCardMini(
            'wood', '木材',
            resourcesInfo.wood.amount,
            resourcesInfo.wood.production,
            'fa-tree',
            'linear-gradient(135deg, #D97706, #B45309)'
        ));

        // 粮食
        container.appendChild(this.createResourceCardMini(
            'food', '粮食',
            resourcesInfo.food.amount,
            resourcesInfo.food.production,
            'fa-leaf',
            'linear-gradient(135deg, #10B981, #059669)'
        ));

        // 人口
        container.appendChild(this.createResourceCardMini(
            'population', '人口',
            `${resourcesInfo.population.current}/${resourcesInfo.population.max}`,
            null,
            'fa-users',
            'linear-gradient(135deg, #8B5CF6, #7C3AED)'
        ));
    }

    createResourceCardMini(id, name, amount, production, icon, gradient) {
        const card = document.createElement('div');
        card.className = 'resource-card-mini';

        const iconDiv = document.createElement('div');
        iconDiv.className = 'resource-icon-mini';
        iconDiv.style.background = gradient;
        iconDiv.style.boxShadow = `0 4px 12px ${gradient.match(/#[A-Fa-f0-9]{6}/)[0]}40`;
        iconDiv.innerHTML = `<i class="fa ${icon}"></i>`;

        const label = document.createElement('div');
        label.className = 'resource-label';
        label.textContent = name;

        const amountDiv = document.createElement('div');
        amountDiv.className = 'resource-amount';
        amountDiv.id = `${id}-amount`;
        amountDiv.textContent = typeof amount === 'number' ? Math.floor(amount) : amount;

        card.appendChild(iconDiv);
        card.appendChild(label);
        card.appendChild(amountDiv);

        if (production !== null) {
            const prodDiv = document.createElement('div');
            prodDiv.className = `resource-production ${production >= 0 ? 'positive' : 'negative'}`;
            prodDiv.textContent = `${production >= 0 ? '+' : ''}${production.toFixed(1)}/h`;
            card.appendChild(prodDiv);
        }

        return card;
    }

    /**
     * 更新建筑显示
     */
    updateBuildingsDisplay() {
        const container = document.getElementById('buildings-list');
        if (!container) return;

        const buildings = this.buildingManager.getVisibleBuildings();
        container.innerHTML = '';

        if (buildings.length === 0) {
            container.innerHTML = '<div class="empty-state"><i class="fa fa-building"></i><p>暂无可用建筑</p></div>';
            return;
        }

        buildings.forEach(building => {
            const info = this.buildingManager.getBuildingDisplayInfo(building.id);
            container.appendChild(this.createBuildingCard(info));
        });
    }

    createBuildingCard(building) {
        const card = document.createElement('div');
        card.className = 'building-card-compact';

        card.innerHTML = `
            <div class="card-header">
                <div class="card-icon">
                    <i class="fa ${GAME_CONFIG.ICONS[building.id] || 'fa-building'}"></i>
                </div>
                <div class="card-info">
                    <div class="card-title">
                        ${building.name}
                        <span class="level-badge">Lv.${building.level}</span>
                    </div>
                    <div class="card-desc">${building.description}</div>
                </div>
            </div>
            ${building.unlocked ? `
                <div style="margin-bottom: 0.75rem;">
                    <div style="display: flex; justify-content: space-between; font-size: 0.85rem; margin-bottom: 0.25rem;">
                        <span style="color: var(--color-text-tertiary);">效率</span>
                        <span style="color: var(--color-primary); font-weight: 600;">${(building.efficiency * 100).toFixed(0)}%</span>
                    </div>
                    <div class="progress-bar">
                        <div class="progress-fill" style="width: ${building.efficiency * 100}%"></div>
                    </div>
                </div>
            ` : ''}
            <div class="cost-display">
                <div class="cost-item">
                    <div class="cost-icon-small" style="background: linear-gradient(135deg, #D97706, #B45309);">
                        <i class="fa fa-tree"></i>
                    </div>
                    <span>${building.unlocked ? building.upgradeCost.wood : building.unlockCost.wood}</span>
                </div>
                <div class="cost-item">
                    <div class="cost-icon-small" style="background: linear-gradient(135deg, #10B981, #059669);">
                        <i class="fa fa-leaf"></i>
                    </div>
                    <span>${building.unlocked ? building.upgradeCost.food : building.unlockCost.food}</span>
                </div>
            </div>
            <button class="btn ${building.unlocked ? 'btn-primary' : 'btn-secondary'} ${(building.unlocked ? building.canUpgrade : building.canUnlock) ? '' : 'disabled'}"
                    data-building="${building.id}"
                    data-action="${building.unlocked ? 'upgrade' : 'unlock'}"
                    ${(building.unlocked ? building.canUpgrade : building.canUnlock) ? '' : 'disabled'}>
                <i class="fa fa-${building.unlocked ? 'arrow-up' : 'unlock'}"></i>
                <span>${building.unlocked ? '升级建筑' : '解锁建筑'}</span>
            </button>
        `;

        const btn = card.querySelector('button');
        if (btn && !btn.disabled) {
            btn.addEventListener('click', () => {
                const action = btn.getAttribute('data-action');
                const id = btn.getAttribute('data-building');
                if (action === 'upgrade') {
                    this.handleBuildingUpgrade(id);
                } else {
                    this.handleBuildingUnlock(id);
                }
            });
        }

        return card;
    }

    /**
     * 更新事件显示
     */
    updateEventsDisplay() {
        const container = document.getElementById('events-list');
        if (!container) return;

        const events = this.eventManager.getAllActiveEventsDisplayInfo();
        container.innerHTML = '';

        if (events.length === 0) {
            container.innerHTML = '<div class="empty-state"><i class="fa fa-bell-slash"></i><p>暂无事件</p></div>';
            this.updateEventsCount();
            return;
        }

        events.forEach(event => {
            container.appendChild(this.createEventCard(event));
        });

        this.updateEventsCount();
    }

    createEventCard(event) {
        const card = document.createElement('div');
        card.className = 'event-card-compact';
        card.style.borderLeft = '4px solid var(--color-accent)';

        let optionsHTML = '';
        if (event.type === 'choice' && event.optionsWithStatus) {
            event.optionsWithStatus.forEach((option, index) => {
                const reqText = option.requirements && Object.keys(option.requirements).length > 0
                    ? `需要: ${Object.entries(option.requirements).map(([k, v]) => `${v}${k === 'wood' ? '木材' : '粮食'}`).join(', ')}`
                    : '';
                optionsHTML += `
                    <button class="btn btn-primary"
                            data-event="${event.id}"
                            data-option="${index}"
                            ${option.canAfford ? '' : 'disabled'}
                            style="margin-top: 0.5rem;">
                        <span>${option.text}</span>
                        ${reqText ? `<span style="font-size: 0.75rem; opacity: 0.8;">(${reqText})</span>` : ''}
                    </button>
                `;
            });
        }

        card.innerHTML = `
            <div class="card-header">
                <div class="card-icon" style="background: linear-gradient(135deg, var(--color-accent), #D97706);">
                    <i class="fa fa-bolt"></i>
                </div>
                <div class="card-info">
                    <div class="card-title" style="color: var(--color-accent);">${event.name}</div>
                    <div class="card-desc">${event.description}</div>
                </div>
            </div>
            ${optionsHTML}
        `;

        card.querySelectorAll('button[data-event]').forEach(btn => {
            if (!btn.disabled) {
                btn.addEventListener('click', () => {
                    const eventId = btn.getAttribute('data-event');
                    const optionIndex = parseInt(btn.getAttribute('data-option'));
                    this.handleEventChoice(eventId, optionIndex);
                });
            }
        });

        return card;
    }

    /**
     * 更新游戏信息
     */
    updateGameInfo() {
        const stageEl = document.getElementById('game-stage');
        if (stageEl) {
            const stageName = GAME_CONFIG.STAGES[this.gameData.currentStage.toUpperCase()]?.name || '生存阶段';
            stageEl.textContent = stageName;
        }

        const popEl = document.getElementById('game-population');
        if (popEl) {
            popEl.textContent = `${this.gameData.resources.population}/${this.gameData.resources.maxPopulation}`;
        }

        const dayEl = document.getElementById('game-day');
        if (dayEl) {
            dayEl.textContent = `第${this.gameData.consecutiveDays || 1}天`;
        }
    }

    updateEventsCount() {
        const countEl = document.getElementById('events-count');
        if (countEl) {
            const count = this.eventManager.getActiveEvents().length;
            countEl.textContent = count;
        }
    }

    /**
     * 添加日志
     */
    addLog(message) {
        const container = document.getElementById('game-log');
        if (!container) return;

        const now = new Date();
        const time = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;

        const entry = document.createElement('div');
        entry.className = 'log-entry';
        entry.innerHTML = `
            <div class="log-time">${time}</div>
            <div class="log-message">${message}</div>
        `;

        container.insertBefore(entry, container.firstChild);

        while (container.children.length > 50) {
            container.removeChild(container.lastChild);
        }
    }

    /**
     * 处理招募村民
     */
    handleRecruitVillager() {
        const result = this.villagerManager.recruitVillager();
        if (result.success) {
            this.saveGame();
            this.updateAllTabs();
            this.addLog(result.message);
            this.showNotification(result.message, 'success');
        } else {
            this.showNotification(result.message, 'error');
        }
    }

    /**
     * 处理建筑升级
     */
    handleBuildingUpgrade(buildingId) {
        const result = this.buildingManager.upgradeBuilding(buildingId);
        if (result.success) {
            this.saveGame();
            this.updateAllTabs();
            this.addLog(result.message);
            this.showNotification(result.message, 'success');
        } else {
            this.showNotification(result.message, 'error');
        }
    }

    /**
     * 处理建筑解锁
     */
    handleBuildingUnlock(buildingId) {
        const result = this.buildingManager.unlockBuilding(buildingId);
        if (result.success) {
            this.saveGame();
            this.updateAllTabs();
            this.addLog(result.message);
            this.showNotification(result.message, 'success');
        } else {
            this.showNotification(result.message, 'error');
        }
    }

    /**
     * 处理事件选择
     */
    handleEventChoice(eventId, optionIndex) {
        const result = this.eventManager.handleEventChoice(eventId, optionIndex);
        if (result.success) {
            this.saveGame();
            this.updateAllTabs();
            this.addLog(result.message);
            this.showNotification(result.message, 'success');
        } else {
            this.showNotification(result.message, 'error');
        }
    }

    destroy() {
        Object.values(this.timers).forEach(timer => {
            if (timer) clearInterval(timer);
        });
        this.saveGame();
        this.isInitialized = false;
    }
}

const gameManager = new GameManager();
export default gameManager;
